<template>
  <div class="bind-page">
    <div v-if="isMerged" class="bind-container">
      <p class="bind-text">
        {{ $t('bindUserRequestSuccess') }}
      </p>
      <x-button class="goback-button" type="default" @click.native="miniprogramBack">{{ $t('goBack') }}</x-button>
    </div>
    <div v-else class="bind-container">
      <p class="bind-text">
        {{ $t('bindUserAuthorizeTips') }}
      </p>
      <x-button class="bind-button" @click.native="bindUser" :disabled="isBinding" :show-loading="isBinding">{{ $t('authorizeRightNow') }}</x-button>
    </div>
  </div>
</template>

<script>
import {
  SCOPE_SNSAPI_USERINFO,
  wechatGetCode,
  wechatMergeUserByCode
} from '@/wxLogin'
import { XButton } from 'vux'

export default {
  data() {
    return {
      isMerged: false,
      isBinding: false,
      redirectUrl: '',
      isTab: false
    }
  },
  methods: {
    bindUser() {
      if (this.isBinding) {
        return 
      }

      this.isBinding = true
      wechatGetCode(SCOPE_SNSAPI_USERINFO)
    },
    miniprogramBack() {
      this.$weixin.ready(() => {

        console.log('miniprogramBack redirectUrl', this.redirectUrl)
        if (this.redirectUrl) {

          if (this.isTab) {
            this.$weixin.miniProgram.switchTab({
              url: this.redirectUrl
            })

            return
          }

          this.$weixin.miniProgram.redirectTo({
            url: this.redirectUrl
          })

          return
        }

        this.$weixin.miniProgram.switchTab({
          url: '/pages/index/index'
        })
      })
    },
    parseMiniProgramUrl(url) {
      const [pathPart, queryPart] = url.split('?')

      const query = {}
      if (queryPart) {
        queryPart.split('&').forEach(pair => {
          const [key, value] = pair.split('=')
          if (key) {
            query[decodeURIComponent(key)] = decodeURIComponent(value || '')
          }
        })
      }

      return {
        path: pathPart,
        query
      }
    },
    buildMiniProgramUrl(path, query = {}) {
      const queryString = Object.keys(query)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(query[key])}`)
        .join('&')

      return queryString ? `${path}?${queryString}` : path
    }

  },
  created() {

    document.title = 'Ghulja Uchur'

    const query = this.$route.query

    if (query.redirect) {
      this.redirectUrl = query.redirect
    }

    if (query.isTab) {
      this.isTab = true
    }

    if (query.code && query.state) {
      this.isBinding = true
      this.$weixin.ready(() => {
        wechatMergeUserByCode(query, SCOPE_SNSAPI_USERINFO, () => {
          this.isMerged = true

          this.$weixin.miniProgram.postMessage({
            data: {
              action: 'user_merged_success',
              data: {
                redirect: this.redirectUrl
              }
            }
          })

          this.miniprogramBack()
        }).catch((error) => {
          this.isBinding = false
          if (error.response && error.response.status === 401) {
            this.$vux.toast.text(this.$t("bindUserRequestFailed"))
          }
        })
      })
    }
  },
  components: {
    XButton
  }
}
</script>

<style scoped>
  .bind-page {
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f7f8fa;
    height: 100%;
  }
  .bind-container {
    flex: 1;
    text-align: center;
    padding: 20px;
    max-width: 300px;
  }
  .bind-text {
    font-size: 16px;
    color: #333;
    margin-bottom: 20px;
    line-height: 1.5;
    padding: 30px 0;
  }
  .bind-button {
    width: 80%;
    padding: 4px 0;
    background-color: #07c160;
    color: #fff;
    font-size: 16px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
  }
  .goback-button {
    width: 80%;
    padding: 4px 0;
    font-size: 16px;
    border: none;
    border-radius: 6px;
    cursor: pointer;
  }
  .bind-button:active {
    background-color: #06ae56;
  }
</style>
